package com.zyd.blog.controller;

import com.alibaba.fastjson.JSONArray;
import com.zyd.blog.business.annotation.BussinessLog;
import com.zyd.blog.business.enums.PlatformEnum;
import com.zyd.blog.homeart.service.ICommentReplyService;
import com.zyd.blog.homeart.service.ICommentService;
import com.zyd.blog.homeart.service.IDesignArticleService;
import com.zyd.blog.homeart.service.IRotationChartService;
import com.zyd.blog.homeart.service.es.esDesignArticleService;
import com.zyd.blog.homeart.util.ResponseObject;
import com.zyd.blog.homeart.util.UuidUtil;
import com.zyd.blog.persistence.beans.*;
import com.zyd.blog.persistence.beans.es.EsDesignArticle;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortOrder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.constraints.NotBlank;
import java.time.Duration;
import java.time.Instant;
import java.util.*;

/**
* <p>
    *  前端控制器
    * </p>
*
* @author liusongqi
* @since 2020-02-12
*/
@RestController
@RequestMapping("/commentReply")
public class CommentReplyController {
    private final Logger logger = LoggerFactory.getLogger(CommentReplyController.class);
    @Autowired
    private ICommentReplyService iCommentReplyService;
    @Autowired
    private ICommentService iCommentService;
    @Autowired
    private ElasticsearchTemplate elasticsearchTemplate;
    @Autowired
    private IDesignArticleService iDesignArticleService;
    @Autowired
    private esDesignArticleService esDesignArticleService;

    @Autowired
    private IRotationChartService iRotationChartService;
    /**
     *     根据评论 id  点赞   点赞数量加1
     * state 0收藏 1点赞 2评论 3分享
     */
    @RequestMapping(value = "/fabulous", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/fabulous 进行点赞 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject fabulous(String commentId,String userId,String state) {
        ResponseObject ob = new ResponseObject();
        if (commentId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论id不可为空");
            return ob;
        }
        if (userId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        if (state.isEmpty()){
            ob.setCode(1);
            ob.setMsg("分类 不可为空");
            return ob;
        }
        Integer sort1;
        try {
            sort1 = iCommentService.fabulous(commentId,userId,state);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(sort1);
        ob.setMsg("success");
        return ob;
    }
    /**
     *     根据评论回复 id  点赞   点赞数量加1
     * state 0收藏 1点赞 2评论 3分享
     */
    @RequestMapping(value = "/fabulousReply", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/fabulousReply 进行点赞 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject fabulousReply(String replyId,String userId) {
        ResponseObject ob = new ResponseObject();
        if (userId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        if (replyId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论回复id为空");
            return ob;
        }
        Integer sort1;
        try {
            sort1 = iCommentService.fabulousReply(replyId,userId);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(sort1);
        ob.setMsg("success");
        return ob;
    }
    /**
     *     根据文章 id  取消评论的点赞   点赞数量减1
     */
    @RequestMapping(value = "/reduceCommentZan", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/reduceCommentZan 取消点赞 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject reduceCommentZan(String commentId,String userId,String state) {
        ResponseObject ob = new ResponseObject();
        if (userId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        if (commentId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论id不可为空");
            return ob;
        }
        if (state.isEmpty()){
            ob.setCode(1);
            ob.setMsg("分类id不可为空");
            return ob;
        }
        Integer integer;
        try {
            integer = iCommentService.reduceCommentZan(commentId,userId,state);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(integer);
        ob.setMsg("success");
        return ob;
    }
    /**
     *     根据文章 id  取消评论回复的点赞   点赞数量减1
     */
    @RequestMapping(value = "/reduceCommentReplyZan", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/reduceCommentReplyZan 取消点赞 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject reduceCommentReplyZan(String replyId,String userId) {
        ResponseObject ob = new ResponseObject();
        if (userId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        if (replyId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论回复id为空");
            return ob;
        }
        Integer integer;
        try {
            integer = iCommentService.reduceCommentReplyZan(replyId,userId);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(integer);
        ob.setMsg("success");
        return ob;
    }
    //添加评论回复
    @RequestMapping(value = "/addCommentReply", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/addCommentReply 添加评论回复 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject addCommentReply(CommentReply commentReply) {
        ResponseObject ob = new ResponseObject();
        if (commentReply.getUserId().isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        Integer sort1;
        try {
            sort1 = iCommentReplyService.addCommentReply(commentReply);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(sort1);
        ob.setMsg("success");
        return ob;
    }
    //删除评论
    @RequestMapping(value = "/deleteComment", method = RequestMethod.POST)
    public ResponseObject deleteComment(String designId,String commentId,String userId,String state) {
        logger.info("/commentReply/deleteComment 删除评论 designId={},commentId={},userId={}",designId,commentId,userId);
        ResponseObject ob = new ResponseObject();
        if (designId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("文章id不可为空");
            return ob;
        }
        if (userId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        if (commentId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论id不可为空");
            return ob;
        }
        if (state.isEmpty()){
            ob.setCode(1);
            ob.setMsg("分类id不可为空");
            return ob;
        }
        Integer sort1;
        try {
            sort1 = iCommentService.deleteComment(designId,commentId,userId,state);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(sort1);
        ob.setMsg("success");
        return ob;
    }
    //删除评论回复
    @RequestMapping(value = "/deleteCommentReply", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/deleteCommentReply 删除评论回复 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject deleteCommentReply(String commentId,String replyId,String userId) {
        logger.info("/commentReply/deleteCommentReply 删除评论回复 commentId={},replyId={},userId={}",commentId,replyId,userId);
        ResponseObject ob = new ResponseObject();
        if (replyId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论回复id不可为空");
            return ob;
        }
        if (userId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("用户id不可为空");
            return ob;
        }
        if (commentId.isEmpty()){
            ob.setCode(1);
            ob.setMsg("评论id不可为空");
            return ob;
        }

        Integer sort1;
        try {
            sort1 = iCommentReplyService.deleteCommentReply(commentId,replyId,userId);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(sort1);
        ob.setMsg("success");
        return ob;
    }

    /**
     * 导入所有姓氏到ES
     */
    @RequestMapping(value = "/importSurnameOrigin", method = RequestMethod.GET)
    public ResponseObject importSongData() {
        logger.info("/commentReply/importSurnameOrigin 入所有姓氏到ES");
        int pageIndex = 1;
        int pageSize = 2000;
        while (true) {
            List<EsDesignArticle> list = iDesignArticleService.getEsDesignArticle(pageIndex, pageSize);
            if (list == null || list.size() == 0) {
                break;
            }
            try {
                int count = 0;
                if (elasticsearchTemplate.indexExists(EsDesignArticle.class)) {
                    elasticsearchTemplate.createIndex(EsDesignArticle.class);
                    elasticsearchTemplate.putMapping(EsDesignArticle.class);
                }
                ArrayList<EsDesignArticle> esDesignArticles = new ArrayList<>();
                for (EsDesignArticle esDesignArticle : list) {
                    esDesignArticles.add(esDesignArticle);
                    if (count % 500 == 0) {
                        esDesignArticleService.saveAll(esDesignArticles);
                        esDesignArticles.clear();
                    }
                    count++;
                }
                //记得提交整除余数不为0时的那部分数据
                if (esDesignArticles.size() > 0) {
                    esDesignArticleService.saveAll(esDesignArticles);
                }
            } catch (Exception e) {
                e.printStackTrace();
                ResponseObject reObj = new ResponseObject();
                reObj.setCode(2);
                reObj.setMsg("导入失败");
                return reObj;
            }
            pageIndex++;
        }
        ResponseObject reObj = new ResponseObject();
        reObj.setCode(0);
        reObj.setMsg("导入成功");
        return reObj;
    }
    /**
     * 搜索输入关键字智能提示-高亮显示
     */
    @RequestMapping(value = "/searchTitle", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/searchTitle 搜索高亮显示 ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject searchSuggest(@NotBlank(message = "关键字不能为空") String keyWord) {
        ResponseObject reObj = new ResponseObject();
        reObj.setCode(0);
        reObj.setData(this.getSearchSuggest(keyWord, new TreeSet<>()));
        reObj.setMsg("success");
        return reObj;
    }
    private List<EsArticle> getSearchSuggest(String keyWord, Set<String> suggestList) {
        int start = 0;
        int size = 10 - suggestList.size();
        // 搜索数据
        SearchRequestBuilder searchRequestBuilder;
        searchRequestBuilder = elasticsearchTemplate.getClient()
                .prepareSearch("design_article").setTypes("EsDesignArticle")
                .setQuery(QueryBuilders.matchQuery("title",keyWord));
        searchRequestBuilder.setFrom(start).setSize(10);
        searchRequestBuilder.addSort("num", SortOrder.DESC);
        //设置高亮数据
        HighlightBuilder hiBuilder = new HighlightBuilder();
        hiBuilder.preTags("<em>");
        hiBuilder.postTags("</em>");
        hiBuilder.field("title");
        searchRequestBuilder.highlighter(hiBuilder);
        //获得查询结果数据
        SearchResponse searchResponse = searchRequestBuilder.get();
        //获取查询结果集
        SearchHits searchHits = searchResponse.getHits();
        // 返回搜索结果
        List<String> list = new ArrayList<>();
        List<String> list1 = new ArrayList<>();
        List<Object> list2 = new ArrayList<>();
        for (SearchHit hit : searchHits) {
            Text[] title = hit.getHighlightFields().get("title").getFragments();
            String sourceAsString = hit.getSourceAsString();
            list1.add(sourceAsString);
            list2.add(hit.getSource().get("title"));
            for (Text str : title) {
                list.add(str.toString());
            }
        }
        List<EsArticle> products = JSONArray.parseArray(list1.toString(), EsArticle.class);
        for (int i = 0; i < products.size(); i++) {
            products.get(i).setTitle(list.get(i));
            products.get(i).setTitleTwo(list2.get(i).toString());
        }
        return products;
    }
    //查找举报的 内容 分类
    @RequestMapping(value = "/reportType", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/reportType 查找举报的  ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject reportType() {
        ResponseObject ob = new ResponseObject();
        List<ReportType> reportTypes;
        try {
            reportTypes = iRotationChartService.reportType();
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(reportTypes);
        ob.setMsg("success");
        return ob;
    }

    //添加举报
    @RequestMapping(value = "/addReport", method = RequestMethod.POST)
    @BussinessLog(value = "/commentReply/addReport 添加举报  ", platform = PlatformEnum.WEB, save = false)
    public ResponseObject addReport(ReportContent reportContent) {
        ResponseObject ob = new ResponseObject();
        Integer reportTypes;
        try {
            reportTypes = iRotationChartService.addReport(reportContent);
        } catch (Exception e) {
            ob.setCode(1);
            ob.setMsg(e.getMessage());
            return ob;
        }
        ob.setCode(0);
        ob.setData(reportTypes);
        ob.setMsg("success");
        return ob;
    }

}
